package com.icongyou.enterprise.talent_analysis.controller;

import com.icongyou.enterprise.common.result.Result;
import com.icongyou.enterprise.talent_analysis.entity.PortraitResponse;
import com.icongyou.enterprise.talent_analysis.entity.dto.StudentFeatureContext;
import com.icongyou.enterprise.talent_analysis.service.AIPortraitEvaluationService;
import com.icongyou.enterprise.talent_analysis.service.PortraitCacheService;
import com.icongyou.enterprise.talent_analysis.service.PortraitService;
import com.icongyou.enterprise.talent_analysis.service.HrTemplatePreferenceService;
import com.icongyou.enterprise.talent_analysis.service.WordCloudService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/portrait")
@RequiredArgsConstructor
@Slf4j
public class PortraitController {

    private final PortraitService portraitService;
    private final AIPortraitEvaluationService aiPortraitService;
    private final PortraitCacheService cacheService;
    private final HrTemplatePreferenceService preferenceService;
    private final WordCloudService wordCloudService;

    // 阶段2：默认画像（优先从缓存读取）
    // 注：如果HR用户设置了模板偏好，则使用其选择的模板
    @GetMapping("/student/{studentId}")
    public Result<PortraitResponse> getDefaultPortrait(
            @PathVariable("studentId") String studentId,
            @RequestParam(value = "hrUserId", required = false) String hrUserId) {
        
        // 如果提供HR用户ID，检查其模板偏好
        String templateId = null;
        if (hrUserId != null) {
            templateId = preferenceService.getCurrentTemplateId(hrUserId);
        }
        
        // 优先从缓存读取
        PortraitResponse cached = cacheService.getFromCache(studentId, templateId);
        if (cached != null) {
            return Result.success(cached);
        }
        
        // 缓存未命中，实时计算并异步更新缓存
        PortraitResponse resp;
        if (templateId == null) {
            resp = portraitService.computeDefaultPortrait(studentId);
        } else {
            resp = aiPortraitService.computeCustomPortrait(studentId, templateId);
        }
        cacheService.asyncUpdateCache(studentId, templateId, resp);
        return Result.success(resp);
    }

    // 阶段3：使用自定义模板的AI辅助画像（优先从缓存读取）
    @PostMapping("/student/{studentId}/custom")
    public Result<PortraitResponse> getCustomPortrait(
            @PathVariable("studentId") String studentId,
            @RequestBody Map<String, String> request) {
        String templateId = request.get("templateId");
        
        // 优先从缓存读取
        PortraitResponse cached = cacheService.getFromCache(studentId, templateId);
        if (cached != null) {
            return Result.success(cached);
        }
        
        // 缓存未命中，实时计算并异步更新缓存
        PortraitResponse resp = aiPortraitService.computeCustomPortrait(studentId, templateId);
        cacheService.asyncUpdateCache(studentId, templateId, resp);
        return Result.success(resp);
    }

    // 教师评价词云图：提取关键词（独立功能，优先从缓存读取）
    @GetMapping("/student/{studentId}/teacher-keywords")
    public Result<java.util.Map<String, Integer>> getTeacherCommentKeywords(
            @PathVariable("studentId") String studentId) {
        java.util.Map<String, Integer> keywords = wordCloudService.getWordCloud(studentId);
        return Result.success(keywords);
    }
    
    // 调试接口：查看学生特征提取结果
    @GetMapping("/student/{studentId}/features")
    public Result<StudentFeatureContext> getStudentFeatures(@PathVariable("studentId") String studentId) {
        StudentFeatureContext features = aiPortraitService.extractStudentFeatures(studentId);
        return Result.success(features);
    }

    // 管理接口：AI推荐数据映射
    @PostMapping("/dimension/recommend-mapping")
    public Result<List<String>> recommendMapping(@RequestBody Map<String, String> request) {
        String dimensionName = request.get("dimensionName");
        String dimensionDescription = request.get("dimensionDescription");
        List<String> recommendations = aiPortraitService.recommendDataMapping(dimensionName, dimensionDescription);
        return Result.success(recommendations);
    }
    
    // HR模板偏好接口：获取当前选择的模板
    @GetMapping("/preference/{hrUserId}")
    public Result<String> getCurrentTemplate(@PathVariable("hrUserId") String hrUserId) {
        String templateId = preferenceService.getCurrentTemplateId(hrUserId);
        return Result.success(templateId);
    }
    
    // HR模板偏好接口：切换模板
    @PostMapping("/preference/switch")
    public Result<Void> switchTemplate(@RequestBody Map<String, String> request) {
        log.info("收到切换模板请求: {}", request);
        String hrUserId = request.get("hrUserId");
        String enterpriseId = request.get("enterpriseId");
        String templateId = request.get("templateId"); // NULL 表示切换回默认模板
        
        log.info("解析参数 - hrUserId: {}, enterpriseId: {}, templateId: {}", hrUserId, enterpriseId, templateId);
        
        try {
            preferenceService.setCurrentTemplate(hrUserId, enterpriseId, templateId);
            log.info("切换模板成功");
            return Result.success();
        } catch (Exception e) {
            log.error("切换模板失败", e);
            return Result.error(500, "切换模板失败: " + e.getMessage());
        }
    }
}
